﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Controls;
using VAdvantage.Utility;
using VAdvantage.Classes;
using VAdvantage.Grids;
using System.Text;
using VAdvantage.Logging;
using System.Data;
using VAdvantage.DataBase;
using System.Collections;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Print;
using System.ComponentModel;
using VAdvantage.Framework;
using System.Threading;
using System.Windows.Data;

namespace VAdvantage.Apps.AForms
{
    public partial class VInOutGen : UserControl, FormPanel, ASyncProcess
    {
        #region Private Variables
        private VComboBox cmbWarehouse;
        private VTextBoxButton vSearchBPartner;
        private int _windowNo = 0;
        private FormFrame _frame;
        private Object m_M_Warehouse_ID = null;
        protected static DataGridColumn[] arrList = null;
        private Object m_C_BPartner_ID = null;
        private String m_whereClause;
        private bool m_selectionActive = true;
        Grids.MyDataGridCheckBoxColumn chk = new MyDataGridCheckBoxColumn();
        #endregion

        private static VLogger log = VLogger.GetVLogger(typeof(VInOutGen).FullName);

        /// <summary>
        /// Default constuctor
        /// </summary>
        public VInOutGen()
        {
            InitializeComponent();
            //CommonFunctions.SetTabProperties(vtabVInOutGen);
            //CommonFunctions.SetStatusBarProperties(statusBar, lblStatusInfo);
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);
        }
        public void Init(int WindowNo, FormFrame frame)
        {

            _windowNo = WindowNo;
            _frame = frame;
            //_frame.Height = App.Current.Host.Content.ActualHeight - 25;
            //_frame.Width = App.Current.Host.Content.ActualWidth;

            Envs.GetCtx().SetIsSOTrx(_windowNo, true);
            GetLookup();
            //DynInit();
            JbInit();
            this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            chk.Click += new RoutedEventHandler(chk_Click);
            chk.PropertyChanged += new PropertyChangedEventHandler(chk_PropertyChanged);

        }


        private void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private void vtabVInOutGen_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (vtabVInOutGen != null)
            {
                int index = vtabVInOutGen.SelectedIndex;
                m_selectionActive = (index == 0);
            }
        }

        public void GetLookup()
        {
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                Lookup wHouseL = MLookupFactory.Get(Envs.GetContext(), _windowNo, 2223, DisplayType.TableDir);
                Lookup _value = MLookupFactory.Get(Envs.GetContext(), _windowNo, 2762, DisplayType.Search);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => FillPicks(wHouseL, _value));
            });
        }

        private void FillPicks(Lookup wHouseL, Lookup _value)
        {
            //	C_OrderLine.M_Warehouse_ID

            cmbWarehouse = new VComboBox("M_Warehouse_ID", true, false, true, wHouseL, 120);
            m_M_Warehouse_ID = cmbWarehouse.GetValue();
            // cmbOrg
            this.cmbWarehouse.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.cmbWarehouse.FormattingEnabled = true;
            //this.cmbWarehouse.Location = new System.Drawing.Point(96, 4);
            this.cmbWarehouse.Name = "cmbOrg";
            this.cmbWarehouse.SelectionChanged += new SelectionChangedEventHandler(cmbWarehouse_SelectionChanged);
            //this.cmbWarehouse.Height =;
            //this.cmbWarehouse.Width = 40;


            // var addCombo = CreateCombo(0,1);
            tabSelect.Children.Add(cmbWarehouse);
            Grid.SetRow(cmbWarehouse, 0);
            Grid.SetColumn(cmbWarehouse, 2);
            cmbWarehouse.Margin = new Thickness(0, 0, 20, 0);
            cmbWarehouse.VerticalAlignment = VerticalAlignment.Top;

            //this.tabSelect.
            //this.tblpOrg.Controls.Add(this.cmbWarehouse, 1, 0);


            //	C_Order.C_BPartner_ID

            vSearchBPartner = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);
            // vBPartner
            //  this.vSearchBPartner.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.vSearchBPartner.HorizontalAlignment = HorizontalAlignment.Stretch;
            // this.vSearchBPartner.Location = new System.Drawing.Point(406, 4);
            this.vSearchBPartner.Name = "vBPartner";
            //this.vSearchBPartner.Size = new System.Drawing.Size(175, 21);
            //this.vSearchBPartner.Height = 
            //this.vSearchBPartner.Width = 40;
            this.vSearchBPartner.TabIndex = 3;
            //this.tblpOrg.Controls.Add(this.vSearchBPartner, 3, 0);
            // var addVtext = CreateTextBox(0, 3);
            tabSelect.Children.Add(vSearchBPartner);
            Grid.SetRow(vSearchBPartner, 0);
            Grid.SetColumn(vSearchBPartner, 5);
            vSearchBPartner.Margin = new Thickness(0, 0, 20, 0);
            vSearchBPartner.VerticalAlignment = VerticalAlignment.Top;
            this.vSearchBPartner.VetoableChangeListener += new EventHandler(this.vSearchBPartner_TextChanged);
            SetBusy(false);

        }

        //private void DynInit()
        //{
        //    arrList = new DataGridColumn[8];
        //    List<GridFieldVO> fieldVOs = new List<GridFieldVO>();
        //    //  set details
        //    fieldVOs.Add(new GridFieldVO("C_Order_ID", "", FieldType.ID));
        //    DataGridTextColumn txt = new DataGridTextColumn();
        //    //  txt.ValueType = typeof(KeyNamePair);
        //    vdgvRecords.Columns.Add(txt);
        //    arrList[0] = txt;
        //    //check box
        //    DataGridCheckBoxColumn chk = new DataGridCheckBoxColumn();
        //    // chk.Header = "Select";
        //    //chk.TrueValue = "True";
        //    //chk.FalseValue = "False";
        //    chk.Header = "";
        //    vdgvRecords.Columns.Add(chk);
        //    arrList[1] = chk;

        //    fieldVOs.Add(new GridFieldVO("AD_Org_ID", Msg.Translate(Envs.GetContext(), "AD_Org_ID"), FieldType.String));
        //    DataGridTextColumn txt1 = new DataGridTextColumn();
        //    txt1.Header = Msg.Translate(Envs.GetContext(), "AD_Org_ID");
        //    vdgvRecords.Columns.Add(txt1);
        //    arrList[2] = txt1;
        //    fieldVOs.Add(new GridFieldVO("C_DocType_ID", Msg.Translate(Envs.GetContext(), "C_DocType_ID"), FieldType.String));
        //    DataGridTextColumn txt2 = new DataGridTextColumn();
        //    txt2.Header = Msg.Translate(Envs.GetBaseAD_Language(), "C_DocType_ID");
        //    vdgvRecords.Columns.Add(txt2);
        //    arrList[3] = txt2;
        //    fieldVOs.Add(new GridFieldVO("DocumentNo", Msg.Translate(Envs.GetContext(), "DocumentNo"), FieldType.String));
        //    DataGridTextColumn txt3 = new DataGridTextColumn();
        //    txt3.Header = Msg.Translate(Envs.GetContext(), "DocumentNo");
        //    vdgvRecords.Columns.Add(txt3);
        //    arrList[4] = txt3;
        //    fieldVOs.Add(new GridFieldVO("C_BPartner_ID", Msg.Translate(Envs.GetContext(), "C_BPartner_ID"), FieldType.String));
        //    DataGridTextColumn txt4 = new DataGridTextColumn();
        //    txt4.Header = Msg.Translate(Envs.GetContext(), "C_BPartner_ID");
        //    vdgvRecords.Columns.Add(txt4);
        //    arrList[5] = txt4;
        //    fieldVOs.Add(new GridFieldVO("DateOrdered", Msg.Translate(Envs.GetContext(), "DateOrdered"), FieldType.DateTime));
        //    DataGridTextColumn txt5 = new DataGridTextColumn();
        //    txt5.Header = Msg.Translate(Envs.GetContext(), "DateOrdered");
        //    vdgvRecords.Columns.Add(txt5);
        //    arrList[6] = txt5;
        //    fieldVOs.Add(new GridFieldVO("TotalLines", Msg.Translate(Envs.GetContext(), "TotalLines"), FieldType.Text));
        //    DataGridTextColumn txt6 = new DataGridTextColumn();
        //    txt6.Header = Msg.Translate(Envs.GetContext(), "TotalLines");
        //    vdgvRecords.Columns.Add(txt6);
        //    arrList[7] = txt6;

        //    //vdgvRecords.ItemsSource =listColumns.AddRange(arrList);


        //    vdgvRecords.Visibility = Visibility.Collapsed;
        //    //vdgvRecords.MultiSelect = true;
        //    //vdgvRecords.AutoSize = true;

        //    //	Info
        //    //lblStatusInfo.Text = Msg.GetMsg(Envs.GetContext(), "InOutGenerateSel");
        //}

        public void Dispose()
        {
            if (_frame != null)
            {
                _frame.Dispose();
            }
            _frame = null;
        }

        void JbInit()
        {
            vlblWarehouse.Content = Msg.Translate(Envs.GetContext(), "M_Warehouse_ID");
            vlblBPartner.Content = Msg.Translate(Envs.GetContext(), "C_BPartner_ID");
            this.tabSel.Header = Msg.GetMsg(Envs.GetContext(), "Select", true);
            this.tabGen.Header = Msg.GetMsg(Envs.GetContext(), "Generate", true);
            //this.tabSelect.Text = Msg.GetMsg(Envs.GetContext(), "Select", true);
            //this.tabGenrate.Text = Msg.GetMsg(Envs.GetContext(), "Generate", true);
            // cmbWarehouse.SelectionChanged += new SelectionChangedEventHandler(cmbWarehouse_SelectionChanged);
            //this.vdgvRecords.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.vdgvRecords_CellClick);
            //vSearchBPartner.VetoableChangeListener += new EventHandler(this.vSearchBPartner_TextChanged);

            //vdgvRecords.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            //vdgvRecords.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            //vdgvRecords.ReadOnly = true;
            //vdgvRecords.AutoGenerateColumns = false;
            //vdgvRecords.BorderStyle = BorderStyle.FixedSingle;
            //// set style properties of datagrid
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);
        }

        void cmbWarehouse_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            log.Info("M_Warehouse_ID" + "=" + cmbWarehouse.SelectedValue);
            m_M_Warehouse_ID = cmbWarehouse.SelectedValue;
            ExecuteQuery();
        }

        public void ExecuteQuery()
        {
            SetBusy(true);
            log.Info("");
            int AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
            //  Create SQL
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                StringBuilder sql = new StringBuilder(
                    "SELECT 'false' as SELECTROW,C_Order_ID as C_ORDER_ID, o.Name as ONAME, dt.Name as DTNAME, DocumentNo as DOCUMENTNO, bp.Name as BPNAME, DateOrdered As DATEORDERED, TotalLines as TOTAL "
                    + "FROM M_InOut_Candidate_v ic, AD_Org o, C_BPartner bp, C_DocType dt "
                    + "WHERE ic.AD_Org_ID=o.AD_Org_ID"
                    + " AND ic.C_BPartner_ID=bp.C_BPartner_ID"
                    + " AND ic.C_DocType_ID=dt.C_DocType_ID"
                    + " AND ic.AD_Client_ID=" + AD_Client_ID);

                if (m_M_Warehouse_ID != null)
                {
                    if (m_M_Warehouse_ID.ToString() != "-1")
                    {
                        sql.Append(" AND ic.M_Warehouse_ID=").Append(m_M_Warehouse_ID);
                    }
                }
                if (m_C_BPartner_ID != null)
                {
                    sql.Append(" AND ic.C_BPartner_ID=").Append(m_C_BPartner_ID);
                }
                //
                sql.Append(" ORDER BY o.Name,bp.Name,DateOrdered");

                DataSet ds = null;
                //  Execute
                try
                {
                    ds = DB.ExecuteDataset(sql.ToString(), null);
                }
                catch
                {

                }
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => GridBind(ds));
            });
        }

        public void GridBind(DataSet ds)
        {
            DataGridTextColumn order = new DataGridTextColumn();
            order.Header = Msg.Translate(Envs.GetContext(), "C_order_ID");
            order.Binding = new System.Windows.Data.Binding("C_ORDER_ID");
            order.Visibility = Visibility.Collapsed;

            vdgvRecords.AutoGenerateColumns = false;
            vdgvRecords.ItemsSource = null;
            vdgvRecords.Columns.Clear();
            chk.Header = Msg.GetMsg(Envs.GetCtx(), "SELECTROW");
            chk.Binding = new System.Windows.Data.Binding("SELECTROW");
            chk.DataPropertyName = "SELECTROW";
            chk.DataGrid = vdgvRecords;
            chk.IsThreeState = false;
            chk.IsReadOnly = false;
            
            vdgvRecords.Columns.Add(chk);

            DataGridTextColumn txt1 = new DataGridTextColumn();
            txt1.Header = Msg.Translate(Envs.GetContext(), "AD_Org_ID");
            txt1.Binding = new System.Windows.Data.Binding("ONAME");
            txt1.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt1);
            DataGridTextColumn txt2 = new DataGridTextColumn();
            txt2.Header = Msg.Translate(Envs.GetBaseAD_Language(), "C_DocType_ID");
            txt2.Binding = new System.Windows.Data.Binding("DTNAME");
            txt2.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt2);
            DataGridTextColumn txt3 = new DataGridTextColumn();
            txt3.Header = Msg.Translate(Envs.GetContext(), "DocumentNo");
            txt3.Binding = new System.Windows.Data.Binding("DOCUMENTNO");
            txt3.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt3);
            DataGridTextColumn txt4 = new DataGridTextColumn();
            txt4.Header = Msg.Translate(Envs.GetContext(), "C_BPartner_ID");
            txt4.Binding = new System.Windows.Data.Binding("BPNAME");
            txt4.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt4);
            DataGridTextColumn txt5 = new DataGridTextColumn();
            txt5.Header = Msg.Translate(Envs.GetContext(), "DateOrdered");
            txt5.Binding = new System.Windows.Data.Binding("DATEORDERED");
            txt5.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt5);
            DataGridTextColumn txt6 = new DataGridTextColumn();
            txt6.Header = Msg.Translate(Envs.GetContext(), "TotalLines");
            txt6.Binding = new System.Windows.Data.Binding("TOTAL");
            txt6.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt6);

            vdgvRecords.Visibility = Visibility.Visible;

            if (ds != null)
            {
                BindingSource source = new BindingSource(ds.Tables[0].GetBindableData(new Connector()));
                vdgvRecords.ItemsSource = source;
            }
            SetBusy(false);
        }

        void chk_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        /// <summary>
        /// Save Selection & return selecion Query or ""
        /// </summary>
        /// <returns>where clause like C_Order_ID IN (...)</returns>
        private String SaveSelection()
        {
            log.Info("");
            //  ID selection may be pending
            //  Array of Integers
            List<int> results = new List<int>();
            BindingSource rowSource = vdgvRecords.ItemsSource as BindingSource;
            int rows = 0;
            //	Get selected entries
            if (rowSource != null)
            {
                rows = rowSource.Count;
            }

            for (int i = 0; i < rows; i++)
            {
                // int id = Util.GetValueOfInt(vdgvRecords.Rows[i].Cells[0].Value);     //  ID in column 0
                int id = Util.GetValueOfInt(((BindableObject)rowSource[i]).GetValue("C_ORDER_ID"));
                //if (id != null && Convert.ToBoolean(vdgvRecords.Rows[i].Cells[1].Value))
                if (id != null && Convert.ToBoolean(((BindableObject)rowSource[i]).GetValue("SELECTROW")))
                {
                    results.Add(id);
                }
            }

            if (results.Count == 0)
            {
                return "";
            }
            log.Config("Selected #" + results.Count);

            //	Query String
            String keyColumn = "C_Order_ID";
            StringBuilder sb = new StringBuilder(keyColumn);
            if (results.Count > 1)
            {
                sb.Append(" IN (");
            }
            else
            {
                sb.Append("=");
            }
            //	Add elements
            for (int i = 0; i < results.Count; i++)
            {
                if (i > 0)
                {
                    sb.Append(",");
                }
                if (keyColumn.EndsWith("_ID"))
                {
                    sb.Append(results[i].ToString());
                }
                else
                {
                    sb.Append("'").Append(results[i].ToString());
                }
            }

            if (results.Count > 1)
            {
                sb.Append(")");
            }
            //
            log.Config(sb.ToString());
            return sb.ToString();
        }

        /// <summary>
        /// Generate Invoices
        /// </summary>
        private void GenerateShipments()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                log.Info("M_Warehouse_ID=" + m_M_Warehouse_ID);
                String trxName = null;
                Trx trx = null;

                //	Reset Selection
                String sql = "UPDATE C_Order SET IsSelected = 'N' "
                + "WHERE IsSelected='Y'"
                + " AND AD_Client_ID=" + Envs.GetCtx().GetAD_Client_ID();
                int no = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, trxName));
                log.Config("Reset=" + no);

                //	Set Selection
                sql = "UPDATE C_Order SET IsSelected = 'Y' WHERE " + m_whereClause;
                no = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, trxName));
                Dispatcher.BeginInvoke(delegate
                    {
                        if (no == 0)
                        {
                            String msg = "No Shipments";     //  not translated!
                            log.Config(msg);
                            //info.setText(msg);

                            vlblStatusInfo.SetStatusLine(msg.ToString());
                            imgBtnOk.IsEnabled = true;
                            imgBtnOk.IsEnabled = true;
                            vimgbtnGenOk.IsEnabled = true;
                            SetBusy(false);
                            return;
                        }
                        log.Info("Set Selection #" + no);
                        m_selectionActive = false;  //  prevents from being called twice
                        vimgbtnGenOk.IsEnabled = true;
                        //   SetBusy(false);
                        vlblStatusInfo.SetStatusLine(Msg.GetMsg(Envs.GetContext(), "InOutGenerateGen"));
                    });
                //	Prepare Process
                int AD_Process_ID = 199;	  // M_InOutCreate - Vframwork.Process.InOutGenerate
                MPInstance instance = new MPInstance(Envs.GetContext(), AD_Process_ID, 0);
                if (!instance.Save())
                {
                    Dispatcher.BeginInvoke(delegate
                     {
                         vlblStatusInfo.SetStatusLine(Msg.GetMsg(Envs.GetContext(), "ProcessNoInstance"));
                         imgBtnOk.IsEnabled = true;
                         imgBtnOk.IsEnabled = true;
                         vimgbtnGenOk.IsEnabled = true;
                         SetBusy(false);
                     });
                    return;
                }
                ProcessInfo pi = new ProcessInfo("VInOutGen", AD_Process_ID);
                pi.SetAD_PInstance_ID(instance.GetAD_PInstance_ID());

                //	Add Parameter - Selection=Y
                MPInstancePara para = new MPInstancePara(instance, 10);

                para.setParameter("Selection", "Y");
                if (!para.Save())
                {
                    Dispatcher.BeginInvoke(delegate
           {
               String msg = "No Selection Parameter added";  //  not translated
               vlblStatusInfo.SetStatusLine(msg.ToString());
               log.Log(Level.SEVERE, msg);
               imgBtnOk.IsEnabled = true;
               imgBtnOk.IsEnabled = true;
               vimgbtnGenOk.IsEnabled = true;
               SetBusy(false);
               return;
           });
                }

                //	Add Parameter - M_Warehouse_ID=x
                para = new MPInstancePara(instance, 20);

                para.setParameter("M_Warehouse_ID", Util.GetValueOfInt(m_M_Warehouse_ID.ToString()));
                if (!para.Save())
                {
                    Dispatcher.BeginInvoke(delegate
           {
               String msg = "No DocAction Parameter added";  //  not translated
               vlblStatusInfo.SetStatusLine(msg.ToString());
               log.Log(Level.SEVERE, msg);
               imgBtnOk.IsEnabled = true;
               imgBtnOk.IsEnabled = true;
               vimgbtnGenOk.IsEnabled = true;
               SetBusy(false);
               return;
           });
                }

                //	Execute Process
                ProcessCtl worker = new ProcessCtl(this, pi, trx);
                worker.Run();     //  complete tasks in unlockUI / generateInvoice_complete
            });

        }

        /// <summary>
        /// Complete generating shipments.
        /// Called from Unlock UI
        /// </summary>
        /// <param name="pi">process info</param>
        private void GenerateShipments_complete(ProcessInfo pi)
        {
            //  Switch Tabs
            //vtabVInOutGen.Invoke(new MethodInvoker(delegate
            //{
            ProcessInfoUtil.SetLogFromDB(pi);

            String sql = "UPDATE C_Order SET IsSelected = 'N' WHERE " + m_whereClause;
            int no = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, null));
            log.Config("Reset=" + no);


            Dispatcher.BeginInvoke(delegate
            {
                vtabVInOutGen.SelectedItem = tabGen;
                vimgbtnGenOk.IsEnabled = false;

                //}));

                //tabGenrate.Focus();
                //

                StringBuilder iText = new StringBuilder();
                iText.Append(pi.GetSummary());
                iText.Append("     (");
                iText.Append(Msg.GetMsg(Envs.GetContext(), "InOutGenerateInfo"));
                iText.Append(" )");
                iText.Append(pi.GetLogInfo(true));

                vtxtHtml.Html = iText.ToString();

                //TextBlock txtShipment = new TextBlock();
                //Grid.SetRow(txtShipment, 0);
                //Grid.SetColumn(txtShipment, 0);
                //Grid.SetColumnSpan(txtShipment, 4);
                //vdgvTable.Children.Add(txtShipment);
                //txtShipment.Text = iText.ToString();








                int[] ids = pi.GetIDs();
                vimgbtnGenOk.IsEnabled = true;
                SetBusy(false);
                if (ids == null || ids.Length == 0)
                {
                    return;
                }
                log.Config("PrintItems=" + ids.Length);

                vimgbtnGenOk.IsEnabled = true;
                // return;
                ShowMessage.AskMessage("PrintShipments", true, "").Closed += (sa, ea) =>
                {
                    //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    if (true.Equals(((Message)sa).DialogResult))
                    {
                        int retValue = VAdvantage.Framework.Message.A_CANCEL;
                        System.Threading.ThreadPool.QueueUserWorkItem(delegate
                        {
                            do
                            {
                                //	Loop through all items
                                bool wait = false;
                                for (int i = 0; i < ids.Length; i++)
                                {
                                    int M_InOut_ID = ids[i];
                                    ReportCtl.StartDocumentPrint(Envs.GetContext(), ReportEngine.SHIPMENT, M_InOut_ID, true);
                                }

                                //ADialogDialog d = new ADialogDialog(m_frame,Env.GetHeader(Env.getCtx(), m_WindowNo),Msg.GetMsg(Env.getCtx(), "PrintoutOK?"),
                                //    JOptionPane.QUESTION_MESSAGE);

                                Dispatcher.BeginInvoke(delegate
                                {
                                    VAdvantage.Framework.Message d = new VAdvantage.Framework.Message(Envs.GetHeader(Envs.GetContext(), _windowNo), Msg.GetMsg(Envs.GetContext(), "PrintoutOK?"), VAdvantage.Framework.Message.MessageType.QUESTION);
                                    d.Show();
                                    d.Closing += (se, ev) =>
                                        {
                                            if (true.Equals(((Message)se).DialogResult))
                                            {
                                                retValue = d.GetReturnCode();
                                                wait = true;
                                            }
                                            else
                                            {
                                                wait = true;
                                            }
                                        };

                                });
                                while (!wait)
                                {
                                    System.Threading.Thread.Sleep(1);
                                }
                            }
                            while (retValue == VAdvantage.Framework.Message.A_CANCEL);
                        });
                    }
                    //setCursor(Cursor.getDefaultCursor());

                    #region CommentdCode
                    //if (true.Equals(((Message)sa).DialogResult))
                    //{
                    //    int retValue = VAdvantage.Framework.Message.A_CANCEL;
                    //    VAdvantage.Framework.Message d = new VAdvantage.Framework.Message(Envs.GetHeader(Envs.GetContext(), _windowNo), Msg.GetMsg(Envs.GetContext(), "PrintoutOK?"), VAdvantage.Framework.Message.MessageType.QUESTION);
                    // //do
                    // //   {
                    //        //	Loop through all items
                    //     ThreadPool.QueueUserWorkItem(delegate
                    //        {
                    //        A: for (int i = 0; i < ids.Length; i++)
                    //            {
                    //                int M_InOut_ID = ids[i];
                    //                ReportCtl.StartDocumentPrint(Envs.GetContext(), ReportEngine.SHIPMENT, M_InOut_ID, true);
                    //            }
                    //            Dispatcher.BeginInvoke(delegate
                    //            {
                    //                d.Show();
                    //                d.Closing += (sender, e) =>
                    //                {
                    //                    if (true.Equals(((Message)sender).DialogResult))
                    //                    {
                    //                        retValue = d.GetReturnCode();
                    //                    }


                    //                };

                    //            });
                    //            if (retValue == VAdvantage.Framework.Message.A_CANCEL)
                    //            {
                    //                goto A;
                    //            }
                    //        });

                    //        //ADialogDialog d = new ADialogDialog(m_frame,Envs.GetHeader(Envs.getCtx(), m_WindowNo),Msg.GetMsg(Envs.getCtx(), "PrintoutOK?"),
                    //        //    JOptionPane.QUESTION_MESSAGE);

                    //        //if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    //        //{
                    //        //    // if user clicks on OK button change the value
                    //        //    retValue = d.GetReturnCode();
                    //        //}

                    //    //}
                    //    //while (retValue == VAdvantage.Framework.Message.A_CANCEL);
                    //}
                    #endregion
                };






            });
            //}));


        }

        /// <summary>
        /// Lock User Interface.
        /// Called from the Worker before processing
        /// </summary>
        /// <param name="pi">process info</param>
        public void LockUI(ProcessInfo pi)
        {
            //this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //this.setEnabled(false);
            //this.Enabled = false;
        }

        /// <summary>
        /// Unlock User Interface.
        /// Called from the Worker when processing is done
        /// </summary>
        /// <param name="pi">result of execute ASync call</param>
        public void UnlockUI(ProcessInfo pi)
        {
            //this.setEnabled(true);
            // this.setCursor(Cursor.getDefaultCursor());
            GenerateShipments_complete(pi);
        }

        /// <summary>
        /// Is the UI locked (Internal method)
        /// </summary>
        /// <returns>true, if UI is locked</returns>
        public bool IsUILocked()
        {
            //return this.isEnabled();
            return this.IsEnabled;
        }

        /// <summary>
        /// Method to be executed async.
        /// Called from the Worker
        /// </summary>
        /// <param name="pi">ProcessInfo</param>
        public void ExecuteASync(ProcessInfo pi)
        {

        }

        void chk_Click(object sender, RoutedEventArgs e)
        {
            int rowsSelected = 0;
            BindingSource rowSource = vdgvRecords.ItemsSource as BindingSource;
            if (vdgvRecords.CurrentColumn.DisplayIndex == 0 && vdgvRecords.SelectedIndex > -1)
            {
                if (rowSource.Count != 0)
                {
                    // Boolean isPressed = Convert.ToBoolean(vdgvRecords.Rows[0].Cells[1].Value);
                    Boolean isPressed = Convert.ToBoolean(((BindableObject)rowSource[0]).GetValue("SELECTROW"));
                    // if (vdgvRecords.Rows[0].Cells[1].Selected)
                    ////if (vdgvRecords.SelectedIndex == 0 && vdgvRecords.CurrentColumn.DisplayIndex == 0)
                    ////{
                    ////    // if (Convert.ToBoolean(vdgvRecords.Rows[0].Cells[1].Value))
                    ////    if (Convert.ToBoolean(((BindableObject)rowSource[0]).GetValue("SELECTROW")))
                    ////    {
                    ////        // vdgvRecords.Rows[0].Cells[1].Value = false;
                    ////        ((BindableObject)vdgvRecords.SelectedItem).SetValue("SELECTROW", "false");
                    ////        ((BindableObject)rowSource[0]).SetValue("SELECTROW", "false");
                    ////    }
                    ////    else
                    ////    {
                    ////        //vdgvRecords.Rows[0].Cells[1].Value = true;
                    ////        ((BindableObject)vdgvRecords.SelectedItem).SetValue("SELECTROW", "true");
                    ////        ((BindableObject)rowSource[0]).SetValue("SELECTROW", "true");
                    ////        rowsSelected++;
                    ////    }
                    ////}
                    //int rows = vdgvRecords.RowCount;
                    bool equals = true;

                    for (int i = 0; i < rowSource.Count; i++)
                    {

                        //equals = isPressed.Equals(vdgvRecords.Rows[i].Cells[1].Value);
                        equals = isPressed.Equals(Convert.ToBoolean(((BindableObject)rowSource[i]).GetValue("SELECTROW")));
                        //if (vdgvRecords.Rows[i].Cells[1].Selected)//&& Convert.ToBoolean(vdgvRecords.Rows[i].Cells[0].Value))
                        if (vdgvRecords.SelectedIndex == i && vdgvRecords.CurrentColumn.DisplayIndex == 0)
                        {

                            // if (Convert.ToBoolean(vdgvRecords.Rows[i].Cells[1].Value))]
                            if (Convert.ToBoolean(((BindableObject)rowSource[i]).GetValue("SELECTROW")))
                            {
                                //vdgvRecords.Rows[i].Cells[1].Value = false;
                                ((BindableObject)vdgvRecords.SelectedItem).SetValue("SELECTROW", "false");
                                ((BindableObject)rowSource[i]).SetValue("SELECTROW", "false");
                            }
                            else
                            {
                                //vdgvRecords.Rows[i].Cells[1].Value = true;
                                ((BindableObject)vdgvRecords.SelectedItem).SetValue("SELECTROW", "true");
                                ((BindableObject)rowSource[i]).SetValue("SELECTROW", "true");
                                rowsSelected++;
                            }
                        }
                    }
                }
                //statusBar.setStatusDB(" " + rowsSelected + " ");
                //lblStatusInfo.Text = rowsSelected.ToString();

            }
        }

        public void vSearchBPartner_TextChanged(object sender, System.EventArgs e)
        {
            //log.Info(e.getPropertyName() + "=" + e.getNewValue());
            m_C_BPartner_ID = vSearchBPartner.Value;
            ExecuteQuery();
        }

        private void imgBtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Dispose();
            return;
        }

        private void imgBtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            imgBtnRefresh.IsEnabled = false;
            SetBusy(true);
            m_whereClause = SaveSelection();
            if (m_whereClause.Length > 0 && m_selectionActive	//	on selection tab
            && m_M_Warehouse_ID != null)
            {
                GenerateShipments();
            }
            else
            {
                Dispose();
                SetBusy(false);
            }
        }

        private void imgBtnOk_Click_1(object sender, RoutedEventArgs e)
        {
            imgBtnOk.IsEnabled = false;
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            m_whereClause = SaveSelection();
            if (m_whereClause.Length > 0 && m_selectionActive	//	on selection tab
            && m_M_Warehouse_ID != null)
            {
                GenerateShipments();
            }
            else
            {
                Dispose();
                SetBusy(false);
            }
        }

        private void vimgbtnGenOk_Click(object sender, RoutedEventArgs e)
        {
            vimgbtnGenOk.IsEnabled = false;
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            m_whereClause = SaveSelection();
            if (m_whereClause.Length > 0 && m_selectionActive	//	on selection tab
            && m_M_Warehouse_ID != null)
            {
                GenerateShipments();
            }
            else
            {
                Dispose();
                SetBusy(false);
            }
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }
    }
}
